package com.softwin.cryptocurrency.demo.security;

import io.grpc.*;

import java.util.concurrent.Executor;

import static io.grpc.Metadata.ASCII_STRING_MARSHALLER;

/**
 * Created by rayt on 10/6/16.
 */
public class JwtCallCredential implements CallCredentials {
  private final String jwt;
  private Metadata.Key<String> JWT_METADATA_KEY = Metadata.Key.of("token", ASCII_STRING_MARSHALLER);
  public JwtCallCredential(String jwt) {
    this.jwt = jwt;
  }

  @Override
  public void applyRequestMetadata(MethodDescriptor<?, ?> methodDescriptor, Attributes attributes, Executor executor, MetadataApplier metadataApplier) {
    executor.execute(() -> {
      try {
        Metadata headers = new Metadata();
        headers.put(JWT_METADATA_KEY, jwt);
        metadataApplier.apply(headers);
      } catch (Throwable e) {
        metadataApplier.fail(Status.UNAUTHENTICATED.withCause(e));
      }
    });
  }

  @Override public void thisUsesUnstableApi() {
  }
}